package ua.kiev.tosik.price.conf;

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class AppConfig {

	private static AppConfig ourInstance = new AppConfig();
	private Properties appProperties;
	private Logger logger = Logger.getLogger(AppConfig.class);
	public static final String configFile = "conf/app.properties";
	private String message;

	public static AppConfig getInstance() {
		return ourInstance;
	}

	private AppConfig() {
		logger.info("Load main config file");
		appProperties = new Properties();
		try {
			appProperties.load( new FileInputStream(configFile) );
		} catch (IOException e) {
			message = e.getLocalizedMessage();
			logger.fatal("Can't find global application config [" + configFile + "]!!!");
		}
	}

	public String get(String name) {
		String value = "";
		try {
			value = (appProperties.getProperty(name) == null)?"":appProperties.getProperty(name);
		} catch (Exception e) {
			logger.warn("Properties " + name + " not found");
		}
		return value;
	}

	public synchronized void set(String key, String value) {
		appProperties.put(key, value);
		try {
			appProperties.store(new FileOutputStream(configFile), "Added by application");
		} catch (IOException e) {
			message = e.getLocalizedMessage();
			logger.error(e.getLocalizedMessage());
		}
	}

	public String getMessage() {
		return message;
	}
}